from django import forms
from django.core.exceptions import ValidationError
from django.shortcuts import render,redirect
from app01 import models
from app01.utils.pagination import  Pagination
from app01.utils.bootstrap import BootStrapModelForm
from app01.utils.encrypt import md5
def admin_list(request):
    """管理员列表"""
    ## 构造搜索条件
    data_dict = {}
    search_data = request.GET.get('q', "")
    if search_data:
        data_dict['username__contains'] = search_data
    ## 去数据库获取数据
    queryset = models.Admin.objects.filter(**data_dict)
    # 添加分页功能
    page_object = Pagination(request, queryset,page_size=3)
    context = {
        'queryset': page_object.page_queryset,
        'page_string': page_object.html(),
        'search_data': search_data,
    }
    return render(request,'admin_list.html',context)



class AdminModelForm(BootStrapModelForm):

    confirm_password = forms.CharField(label="确认密码"
                                       ,widget=forms.PasswordInput  ## 隐藏密码
                                       ### 如果不想之后密码错了，将输入的内容置空可以 forms.passwordInput(rendr_value=True)
                                       )
    class Meta:
        model = models.Admin
        fields = ['username','password','confirm_password']
        widgets = {
            'password': forms.PasswordInput()
        }
    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        ## 将首次输入的密码进行md5加密
        return md5(pwd)

    def clean_confirm_password(self):

        pwd = self.cleaned_data.get('password')
        ## 再次确认的密码也要进行MD5加密
        confirm = md5( self.cleaned_data.get('confirm_password'))
        if confirm != pwd:
            raise  ValidationError("密码不一致，请重新输入！！")
        # 返回什么，此字段，之后保存到数据库中的就是什么
        return confirm

class AdminEditModelForm(BootStrapModelForm):
    class Meta:
        model = models.Admin
        fields = ['username']

class AdminResetModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(label="确认密码"
                                       ,widget=forms.PasswordInput  ## 隐藏密码
                                       ### 如果不想之后密码错了，将输入的内容置空可以 forms.passwordInput(rendr_value=True)
                                       )
    class Meta:
        model = models.Admin
        fields = ['password']
        widgets = {
            'password': forms.PasswordInput(render_value="True")
        }

    def clean_password(self):
        # 获取新密码并加密
        pwd = self.cleaned_data.get('password')
        md5_pwd = md5(pwd)

        # 校验新密码是否与当前密码一致
        # 检查当前用户（self.instance）是否与新密码相同
        if md5_pwd == self.instance.password:
            raise ValidationError("新密码不能与当前密码相同")

        # 检查是否有其他用户使用相同的密码（除当前用户外）
        exists = models.Admin.objects.exclude(id=self.instance.pk).filter(password=md5_pwd).exists()
        if exists:
            raise ValidationError("密码不能与其他用户的密码重复")

        return md5_pwd

    def clean_confirm_password(self):

        pwd = self.cleaned_data.get('password')
        ## 再次确认的密码也要进行MD5加密
        confirm = md5( self.cleaned_data.get('confirm_password'))
        if confirm != pwd:
            raise  ValidationError("密码不一致，请重新输入！！")
        # 返回什么，此字段，之后保存到数据库中的就是什么
        return confirm
def admin_add(request):
    """"添加管理员"""
    title = "新建管理员"
    if request.method == "GET":
        form = AdminModelForm()
        return render(request,'change.html',{'form':form, "title":"新建管理员"})

    form = AdminModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')
    return render(request,'change.html',{'form':form, "title":title})
def admin_edit(request,nid):
    """编辑管理员"""
    row_object = models.Admin.objects.filter(id=nid).first()
    if not row_object:
        return render(request,"error.html", {"msg":"数据不存在"})

    title = "编辑管理员"
    if request.method == "GET":
        form = AdminEditModelForm(instance=row_object)
        return render(request, 'change.html', {"form":form,"title": title})

    form = AdminEditModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')
    render(request,'change.html',{"form":form, "title":title})

def admin_delete(request,nid):
    models.Admin.objects.filter(id=nid).delete()
    return redirect("/admin/list/")


def admin_reset(request, nid):
    """重置密码"""
    # 查找指定 ID 的管理员对象
    row_object = models.Admin.objects.filter(id=nid).first()

    # 如果找不到该管理员，重定向回管理员列表页面
    if not row_object:
        return redirect('/admin/list/')

    title = "重置密码 - {}".format(row_object.username)

    # 处理 GET 请求时，显示重置密码的表单
    if request.method == "GET":
        form = AdminResetModelForm(instance=row_object)  # 通过实例化现有对象加载表单
        return render(request, 'change.html', {"form": form, "title": title})

    # 处理 POST 请求时，提交表单数据
    form = AdminResetModelForm(data=request.POST, instance=row_object)  # 确保传递了当前对象
    if form.is_valid():
        # 仅更新密码字段，确保不修改其他字段
        #row_object.password = form.cleaned_data['password']  # 使用表单中的密码字段
        row_object.save()  # 保存更新后的对象
        return redirect('/admin/list/')

    # 如果表单验证失败，重新渲染表单并显示错误信息
    return render(request, 'change.html', {"form": form, "title": title})